using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;
using System.Text;

using Styx;
using Styx.CommonBot;
using Styx.CommonBot.Routines;
using Styx.Helpers;
using Styx.TreeSharp;
using Styx.WoWInternals;
using Styx.WoWInternals.WoWObjects;
using Styx.Common.Helpers;
using Styx.Pathing;

using CommonBehaviors.Actions;

using Singular.Dynamics;
using Singular.Helpers;
using Singular.Managers;
using Singular.Settings;

using Action = Styx.TreeSharp.Action;
//
using Rest = Singular.Helpers.Rest;
//
using LocationRetriever = Singular.Helpers.LocationRetriever;
using yoyo;

namespace Retadin
{
    public class Routine : CombatRoutine
    {
        /// <summary>
        /// The name of this CombatRoutine
        /// </summary>
        /// <value>
        /// The name.
        /// </value>
        public override string Name { get { return "Retadin2.0"; } }


        /// <summary>
        /// The <see cref="T:Styx.WoWClass"/> to be used with this routine
        /// </summary>
        /// <value>
        /// The class.
        /// </value>
        public override WoWClass Class { get { return WoWClass.Paladin; } }

        public override bool WantButton { get { return true; } }

         public override void OnButtonPress()
        {
            //Logger.Write(Colors.Yellow, "Config opened!");
            yoyo.yoyoForm1 myConfig = new yoyo.yoyoForm1();
            myConfig.ShowDialog();
        }

       private Composite _combat, _buffs;


        public override Composite CombatBehavior { get { return _combat; } }
        public override Composite PreCombatBuffBehavior { get { return _buffs; } }
        public override Composite CombatBuffBehavior { get { return _buffs; } }

		private bool IsTargetBoss()
        {
            if (StyxWoW.Me.CurrentTarget.CreatureRank == WoWUnitClassificationType.WorldBoss ||
               (StyxWoW.Me.CurrentTarget.Level >= 90 && StyxWoW.Me.CurrentTarget.Elite && StyxWoW.Me.CurrentTarget.MaxHealth > 8000000))
                return true;

            else return false;
        }
		
		private int addCount()
        {
            int count = 0;
            foreach (WoWUnit u in ObjectManager.GetObjectsOfType<WoWUnit>(true, true))
            {
                if (u.IsAlive
                    && StyxWoW.Me.CurrentTarget != null
                    && u.Guid != StyxWoW.Me.Guid
                    && !u.IsFriendly
                    && (u.IsHostile || u.IsNeutral)
                    && !u.IsCritter
                    && u.Location.Distance(StyxWoW.Me.Location) <= 8
                    && (u.IsTargetingMyPartyMember || u.IsTargetingMyRaidMember || u.IsTargetingMeOrPet || u.IsTargetingAnyMinion))
                {
                    count++;
                }
            }
            return count;
        }

		private int HSaddCount()
        {
            int count = 0;
            foreach (WoWUnit u in ObjectManager.GetObjectsOfType<WoWUnit>(true, true))
            {
                if (u.IsAlive
                    && StyxWoW.Me.CurrentTarget != null
                    && u.Guid != StyxWoW.Me.Guid
                    && !u.IsFriendly
                    && (u.IsHostile || u.IsNeutral)
                    && !u.IsCritter
                    && u.IsWithinMeleeRange
                    && (u.IsTargetingMyPartyMember || u.IsTargetingMyRaidMember || u.IsTargetingMeOrPet || u.IsTargetingAnyMinion))
                {
                    count++;
                }
            }
            return count;
        }

        public override void Initialize()
        {
            _combat = CreateCombat();
            _buffs = CreateBuffs();
        }


        Composite CreateBuffs()
        {
            return new PrioritySelector(
				Cast("Seal of Truth", ret => !StyxWoW.Me.HasAura("Seal of Truth")),
				Cast("Blessing of Might", ret => (!StyxWoW.Me.HasAura("Blessing of Might") && !StyxWoW.Me.Mounted)),
				Cast("Sacred Shield", ret => (!StyxWoW.Me.HasAura("Sacred Shield") && !StyxWoW.Me.Mounted) && (!StyxWoW.Me.HasAura("Drink") || !StyxWoW.Me.HasAura("Food"))),
				new Decorator(ret =>
					!StyxWoW.Me.HasAura("Visions of Insanity"),
					new Action(abc =>
					{
						WoWItem item = StyxWoW.Me.BagItems.Find(ret => ret.Entry == 86569);
                            if (item != null) item.Use(); 
					}))
				//Cast("Crystal of Insanity", ret => (!StyxWoW.Me.HasAura("Visions of Insanity") && !StyxWoW.Me.Mounted))
			);
        }


        Composite CreateCombat()
        {
			return new Decorator ( ctz => !StyxWoW.Me.Mounted && !StyxWoW.Me.HasAura("Drink") && !StyxWoW.Me.HasAura("Food") && !StyxWoW.Me.HasAura("First Aid"),
				new PrioritySelector(
				//Movement
				new Decorator ( ctt =>!yoyoSettings.myPrefs.DisableAllMovement && !StyxWoW.Me.CurrentTarget.IsWithinMeleeRange,				
				new Action(ret => 
				{ 
                        Navigator.MoveTo(StyxWoW.Me.CurrentTarget.Location);
				})),
				new Action(ret => 
				{ 
                    if (!yoyoSettings.myPrefs.DisableAllMovement && StyxWoW.Me.CurrentTarget.IsWithinMeleeRange && StyxWoW.Me.IsMoving)
                    {
                        WoWMovement.MoveStop();
						//return;
                    };
					return RunStatus.Failure;
				}),
				//Facing
				new Action(ret => 
				{ 
					if (!yoyoSettings.myPrefs.DisableAllFacement)
					{
						StyxWoW.Me.CurrentTarget.Face();
					};
					return RunStatus.Failure; 
				}),

				Cast("Seal of Truth", ret => !StyxWoW.Me.HasAura("Seal of Truth")),

                // Interrupt please.
                Cast("Rebuke", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast),
                Cast("Fist of Justice", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast && SpellManager.Spells["Rebuke"].Cooldown),
                Cast("Hammer of Justice", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast && SpellManager.Spells["Rebuke"].Cooldown),
                Cast("Arcane Torrent", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast && SpellManager.Spells["Rebuke"].Cooldown && 
					(SpellManager.Spells["Fist of Justice"].Cooldown || SpellManager.Spells["Hammer of Justice"].Cooldown)),
                Cast("Blinding Light", ret => StyxWoW.Me.CurrentTarget.IsCasting && StyxWoW.Me.CurrentTarget.CanInterruptCurrentSpellCast && SpellManager.Spells["Rebuke"].Cooldown && 
					(SpellManager.Spells["Fist of Justice"].Cooldown || SpellManager.Spells["Hammer of Justice"].Cooldown) && SpellManager.Spells["Arcane Torrent"].Cooldown),

				// Defensive/Healing CD
				//Cast("Sacred Shield", ret => StyxWoW.Me.HealthPercent < 55),
				Cast("Word of Glory", ret => StyxWoW.Me.HealthPercent < 55 && StyxWoW.Me.CurrentHolyPower >= 3),
				Cast("Divine Protection", ret => StyxWoW.Me.HealthPercent < 90),
				Cast("Hand of Salvation", ret => StyxWoW.Me.HealthPercent < 50 && !StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Hand of Salvation")),
				Cast("Blinding Light", ret => StyxWoW.Me.HealthPercent < 65),
				Cast("Devotion Aura", ret => StyxWoW.Me.HealthPercent < 75),
				Cast("Divine Shield", ret => StyxWoW.Me.HealthPercent < 30),
				Cast("Lay on Hands", ret => StyxWoW.Me.HealthPercent < 15),
				Cast("Hand of Protection", ret => StyxWoW.Me.HealthPercent < 30 && SpellManager.Spells["Divine Shield"].Cooldown),
				//Cast("Anti-Magic Shell", ret => !StyxWoW.Me.HasAura("Anti-Magic Zone") && StyxWoW.Me.HealthPercent < 70),
				Spell.CastOnGround("Light's Hammer", ctx => StyxWoW.Me.Location, 
					ret => StyxWoW.Me.HealthPercent < 75),
				//Cast("Avenging Wrath", ret => IsTargetBoss()),
				//Cast("Guardian of Ancient Kings", ret => IsTargetBoss()),
				
				Cast("Inquisition", ret => (!StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Inquisition") || StyxWoW.Me.GetAuraTimeLeft("Inquisition", true).Seconds <= 3) &&
                                    (StyxWoW.Me.CurrentHolyPower >= 3 || StyxWoW.Me.ActiveAuras.Any(u => u.Key == "Divine Purpose"))), 

				//Cast("Death Strike", ret => !StyxWoW.Me.HasAura("Blood Shield") || 
				//	StyxWoW.Me.ActiveAuras["Blood Shield"].TimeLeft.TotalSeconds < 3 ||
				//	StyxWoW.Me.HealthPercent < 90),


				//Cast("Dancing Rune Weapon", ret => IsTargetBoss()),// || StyxWoW.Me.CurrentRunicPower >= 70),
				//Cast("Raise Dead", ret => IsTargetBoss()),
				

                // Aoe if we got more than 2 mobs to get to killing.
                //new Decorator(ret => UnfriendlyUnits.Count() >= 2,
                //   CreateAoe()),

				//AOE ================
				new Decorator( ret => addCount() > 2,
					new PrioritySelector(
						Cast("Divine Storm", ret => StyxWoW.Me.CurrentHolyPower >= 5),
						Cast("Hammer of Wrath"),
						//Cast("Blood Boil", ret=> StyxWoW.Me.Buffs.ContainsKey("Crimson Scourge") ||//),
						//	Me.HasActiveAura("Crimson Scourge") || StyxWoW.Me.HasAura(81141)),
						Cast("Hammer of the Righteous", ret => StyxWoW.Me.CurrentTarget.IsWithinMeleeRange && addCount() > 4),
						Cast("Exorcism"),
						Cast("Crusader Strike", ret => StyxWoW.Me.CurrentTarget.IsWithinMeleeRange),
						//Spell.CastOnGround("Death and Decay", ret => StyxWoW.Me.CurrentTarget.Location, ret => addCount() > 2),
						Cast("Judgment"),
						Cast("Divine Storm", ret => StyxWoW.Me.CurrentHolyPower >= 3)
						//Cast("Horn of Winter"),
						//Cast("Blood Boil", ret=> StyxWoW.Me.DeathRuneCount > 1)
					)
				), //&& StyxWoW.Me.HasAura("Crimson Scourge")),
				//Cast("Heart Strike", ret => StyxWoW.Me.BloodRuneCount > 0 || HSaddCount() == 2),
				// ===================
						Cast("Templar's Verdict", ret => StyxWoW.Me.CurrentHolyPower >= 5 && StyxWoW.Me.CurrentTarget.IsWithinMeleeRange),
						Cast("Hammer of Wrath"),
						//Cast("Blood Boil", ret=> StyxWoW.Me.Buffs.ContainsKey("Crimson Scourge") ||//),
						//	Me.HasActiveAura("Crimson Scourge") || StyxWoW.Me.HasAura(81141)),
						Cast("Crusader Strike", ret => StyxWoW.Me.CurrentTarget.IsWithinMeleeRange),
						Cast("Exorcism"),
						//Spell.CastOnGround("Death and Decay", ret => StyxWoW.Me.CurrentTarget.Location, ret => addCount() > 2),
						Cast("Judgment"),
						Cast("Execution Sentence"),
						Cast("Templar's Verdict", ret => StyxWoW.Me.CurrentTarget.IsWithinMeleeRange)
			));
        }

        void UseTrinkets()
        {
            var firstTrinket = StyxWoW.Me.Inventory.Equipped.Trinket1;
            var secondTrinket = StyxWoW.Me.Inventory.Equipped.Trinket2;


            if(firstTrinket != null && CanUseEquippedItem(firstTrinket))
                firstTrinket.Use();


            if(secondTrinket != null && CanUseEquippedItem(secondTrinket))
                secondTrinket.Use();


        }
        private static bool CanUseEquippedItem(WoWItem item)
        {
            // Check for engineering tinkers!
            string itemSpell = Lua.GetReturnVal<string>("return GetItemSpell(" + item.Entry + ")", 0);
            if (string.IsNullOrEmpty(itemSpell))
                return false;


            return item.Usable && item.Cooldown <= 0;
        }


        IEnumerable<WoWUnit> UnfriendlyUnits
        {
            get { return ObjectManager.GetObjectsOfType<WoWUnit>(true, false).Where(u => !u.IsDead && u.CanSelect && u.Attackable && !u.IsFriendly && u.IsWithinMeleeRange); }
        }

        private delegate T Selection<out T>(object context);
        Composite Cast(string spell, Selection<bool> reqs = null)
        {
            return
                new Decorator(
                    ret => ((reqs != null && reqs(ret)) || (reqs == null)) && SpellManager.CanCast(spell),
                    new Action(ret => SpellManager.Cast(spell)));
        }


        public static TimeSpan GetSpellCooldown(string spell)
        {
            SpellFindResults results;
            if (SpellManager.FindSpell(spell, out results))
            {
                if (results.Override != null)
                    return results.Override.CooldownTimeLeft;
                return results.Original.CooldownTimeLeft;
            }


            return TimeSpan.MaxValue;
        }
    }
}